//
//  MessageViewController.m
//  JiuLe
//
//  Created by xcq on 15/11/2.
//  Copyright © 2015年 Fine. All rights reserved.
//
#import "Common.h"
#import "RESideMenu.h"
#import "MessageModel.h"
#import "JlUserManager.h"
#import "VRGCalendarView.h"
#import "UWDatePickerView.h"
#import "LoginViewController.h"
#import "MessageTableViewCell.h"
#import "MessageViewController.h"
#import "MessageMapViewController.h"
#define TabbarItemNums 5.f
#define CellHeight 51
static NSString *cellIdentifier = @"messageCell";
@interface MessageViewController() <UITableViewDelegate,VRGCalendarViewDelegate,UITableViewDataSource> {
    NSDateFormatter *dateFormatter;
}
@property (nonatomic, strong) UIView *maskView;
@property (nonatomic, strong) NSMutableArray *showDataSouce;
@property (nonatomic, strong) DropDownView *dropView;
@property (nonatomic, strong) VRGCalendarView *pickerView;
@end

@implementation MessageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"消息";
    _unreadCount = 0;
    _index = -1;
    addObserver(@selector(netRequest:), RefreshMessageViewController);
    addObserver(@selector(createTabBarRedPoint), CreatMessageRedPoint);
    addObserver(@selector(getCorrespondenceMessage:), HomePagePostMessageReloadWithType);
    if (dateFormatter == nil) {
        dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    }
    [self showNavBarLeftImgAndRightTitle:nil
                            andRightImge:[UIImage imageNamed:@"arr_up"]
                       andRightSeleteImg:[UIImage imageNamed:@"arr_down"]
                          andRightAction:@selector(RightBtnAction:)
                           andLeftAction:@selector(leftBtnAction)
                             andLeftImge:[UIImage imageNamed:@"dateBtn"]
                        andLeftSeleteImg:nil];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"MessageTableViewCell"
                                               bundle:nil]
         forCellReuseIdentifier:cellIdentifier];
    _tableView.estimatedRowHeight = 60;
    _tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.tableFooterView = [UIView new];
    [self netRequest:[dateFormatter stringFromDate:[NSDate date]]];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
}


- (void)viewWillDisappear:(BOOL)animated {
    if (_index != -1 && _unreadCount > 0) {
        MessageModel *model = [_showDataSouce objectAtIndex:_index];
        [InterfaceNetManager MessageReadStatusChange:model.id completion:^(BOOL isSucceed,
                                                                           NSString *message,
                                                                           id data,
                                                                           NSError *error) {
            if (isSucceed) {
                _unreadCount -= 1;
                _index = -1;
                if (_unreadCount == 0) {
                    [self remoteTabBarRedPoint];
                    postNotification(@"refreshHome");
                }
            }
        }];
    }
}



- (void)createTabBarRedPoint {
    [Common createRedPointToTabBar:1];
}

- (void)remoteTabBarRedPoint {
    [Common removeRedPoint:1];
}

- (void)getCorrespondenceMessage:(NSNotification *)notifacation {
    if (_tableView == nil || _dataSouce == nil) {
        return;
    }
    if (_dataSouce == nil ) {
        _dataSouce = [NSMutableArray new];
    } else {
        [_dataSouce removeAllObjects];
    }
    NSString *str = notifacation.object;
    if (str != nil && ![str isEqualToString:@""]) {
        if ([str componentsSeparatedByString:@" "].count > 1) {
            str = [[str componentsSeparatedByString:@" "] firstObject];
        }
    } else {
        str = [dateFormatter stringFromDate:[NSDate date]];
    }
    [SVProgressHUD showWithStatus:@"加载中.."];
    [InterfaceNetManager RequestUserNewMessage:^(BOOL isSucceed,
                                                 NSString *message,
                                                 id data,
                                                 NSError *error) {
        if (isSucceed) {
            [self dataHandle:[data objectForKey:@"warnlist"]];
            [self pushMessageContentController];
            postNotification(@"refreshHome");
        } else {
            //TODO:
            [self removeRedPoint];
        }
        [SVProgressHUD dismiss];
    } DateStr:str];
}

- (void)netRequest:(NSString *)date {
    BOOL homeCellClick = [[[NSUserDefaults standardUserDefaults] objectForKey:FirstJoinAppClickHomeCellGoMessage] boolValue];
    if (_dataSouce == nil ) {
        _dataSouce = [NSMutableArray new];
    } else {
        [_dataSouce removeAllObjects];
    }
    if (![date isKindOfClass:[NSString class]]) {
        date = [dateFormatter stringFromDate:[NSDate date]];
    }
    [SVProgressHUD showWithStatus:@"加载中.."];
    [InterfaceNetManager RequestUserNewMessage:^(BOOL isSucceed,
                                                 NSString *message,
                                                 id data,
                                                 NSError *error) {
        if (isSucceed) {
            [self dataHandle:[data objectForKey:@"warnlist"]];
            if (homeCellClick) {
                [self pushMessageContentController];
            }
        } else {
            //TODO:
            [self removeRedPoint];
        }
        [SVProgressHUD dismiss];
    } DateStr:date];
}

- (void)dataHandle:(NSArray *)dataSource {
     [_showDataSouce removeAllObjects];
      _unreadCount = 0;
     if (dataSource.count > 0) {
        for (int i = 0 ; i < dataSource.count ; i++) {
            MessageModel *model = [MessageModel objectWithKeyValues:dataSource[i]];
            model.date = [NSDate dateWithTimeIntervalSince1970:[model.time longLongValue]];
            [self.dataSouce addObject:model];
            if ([model.read integerValue] == 0) {
                _unreadCount += 1;
            }
        }
        if (_tableView.delegate == nil) {
            _tableView.delegate = self;
            _tableView.dataSource = self;
        }
         if (_unreadCount > 0) {
             [self createTabBarRedPoint];
         } else {
             [self remoteTabBarRedPoint];
         }
    } else {
        [self remoteTabBarRedPoint];
    }
    _showDataSouce = [self.dataSouce mutableCopy];
    [_tableView reloadData];
}

- (void)pushMessageContentController {
    if (_showDataSouce.count == 1 && [JlUserManager shareInstance].baseTab.selectedIndex == 1) {
        MessageMapViewController *messageMap = [[MessageMapViewController alloc] initWithNibName:@"MessageMapViewController" bundle:nil];
        messageMap.model = [_showDataSouce firstObject];
        _index = 0;
        [[NSUserDefaults standardUserDefaults] setObject:@(NO) forKey:FirstJoinAppClickHomeCellGoMessage];
        [self.navigationController pushViewController:messageMap animated:NO];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _showDataSouce.count == 0 ? 0 : _showDataSouce.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MessageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
    MessageModel *model = [_showDataSouce objectAtIndex:indexPath.row];
    if ([model.type integerValue] == 1) {
        cell.messageName.text = @"紧急呼叫";
    } else if ([model.type integerValue] == 2) {
        cell.messageName.text = @"健康报警";
    } else if ([model.type integerValue] == 3) {
        cell.messageName.text = @"生命预警";
    } else {
        cell.messageName.text = @"跌倒报警";
    }
    cell.content.text = cell.messageName.text;
    cell.model = model;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return CellHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    MessageTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (cell.hidden == NO) {
        cell.readStatus.hidden = YES;
    }
    _index = indexPath.row;
    MessageMapViewController *messageMap = [[MessageMapViewController alloc] initWithNibName:@"MessageMapViewController" bundle:nil];
    messageMap.model = _showDataSouce[indexPath.row];
    [self.navigationController pushViewController:messageMap animated:YES];
}


- (void)leftBtnAction
{
    [self setupDateView:DateTypeOfStart];
}

- (void)RightBtnAction:(id)sender {
    UIButton *btn = (UIButton *)sender;
    if (_dropView == nil) {
        _dropView = [[DropDownView alloc] initWithFrame:CGRectMake(KScreenWidth - 110, 2, 100, 175
                                                                   )];
        [self.view addSubview:_dropView];
        WS(weakSelf);
        _dropView.action = ^(NSInteger index, NSString *title){
            [weakSelf changeMessageTypeIndex:index
                                    andTitle:title];
        };
        btn.selected = YES;
    } else {
        _dropView.hidden = !_dropView.hidden;
        btn.selected = !btn.selected;
    }
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
}

- (void)setupDateView:(DateType)type {
    if (_pickerView == nil) {
        _maskView = [[UIView alloc] initWithFrame:self.view.bounds];
        [_maskView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self
                                                                                action:@selector(hiddenPickerView)]];
        _maskView.backgroundColor = [[UIColor grayColor] colorWithAlphaComponent:0.4];
        [self.view addSubview:_maskView];
        _maskView.tag = 0x22;
        _pickerView = [[VRGCalendarView alloc] initWithFrame:CGRectMake(CGRectGetWidth(self.view.bounds)/2 - kVRGCalendarViewWidth/2, CGRectGetHeight(self.view.frame)/2 - 271 / 2, kVRGCalendarViewWidth, 0)];
        _pickerView.delegate = self;
        [self.view addSubview:_pickerView];
    } else {
        [self hiddenPickerView];
        [self.view addSubview:_pickerView];
    }
    
}

- (void)hiddenPickerView {
    _pickerView.hidden = !_pickerView.hidden;
    _maskView.hidden = _pickerView.hidden;
}

#pragma mark - VRGCalendarView Delegate
-(void)calendarView:(VRGCalendarView *)calendarView
    switchedToMonth:(int)month
       targetHeight:(float)targetHeight
           animated:(BOOL)animated {
}

-(void)calendarView:(VRGCalendarView *)calendarView dateSelected:(NSDate *)date {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *dateStr = [formatter stringFromDate:date];
    [self.dataSouce removeAllObjects];
    [SVProgressHUD showWithStatus:@"加载中.."];
    [InterfaceNetManager RequestUserNewMessage:^(BOOL isSucceed, NSString *message, id data, NSError *error) {
        if (isSucceed) {
            [self dataHandle:[data objectForKey:@"warnlist"]];
        }
        [SVProgressHUD dismiss];
    } DateStr:dateStr];
    [self hiddenPickerView];
}

- (void)changeMessageTypeIndex:(NSInteger)index
                      andTitle:(NSString *)title {
    _dropView.hidden = !_dropView.hidden;
    //TODO:切换内容
    if (index == 0) {
        [_showDataSouce removeAllObjects];
        _showDataSouce = [_dataSouce mutableCopy];
    } else {
        [_showDataSouce removeAllObjects];
        for (NSInteger i = 0,j = _dataSouce.count; i < j; i ++) {
            MessageModel *model = _dataSouce[i];
            if (index == [model.type integerValue]) {
                [_showDataSouce addObject:model];
            }
        }
    }
    [self.tableView reloadData];
}

- (void)dealloc {
    removeObserver();
}

@end
